import sys
import signal
from .utils import Utils
from .board import Board
from .robot import Robot
import app as app_defs

class Init:

    def __init__(self):
        signal.signal(signal.SIGINT, self.sigint_handler)
        signal.signal(signal.SIGTERM, self.sigint_handler)
        self.app = dir(app_defs)
        self.app_defs = app_defs
        self.utils = Utils(self)
        self.board = Board(self)
        self.robot = Robot(self)

    # 监听程序退出事件
    def sigint_handler(self, signum, frame):
        exit_func = "on_exit"
        if exit_func in self.app:
            getattr(self.app_defs, exit_func)(self)
        self.utils.log.warning("程序退出");
        sys.exit()

    # 通过串口方式连接设备
    def connect_device(self, connect_type, address, port):
        self.utils.device.connect_device(connect_type, address, port)

    # 输出调试日志
    def log(self, data):
        log = {"command": "run:debug", "body": data}
        self.utils.service.write(log)
        self.utils.log.debug(data);
